package org.rency.crawler.dal.dao.impl;

import com.mongodb.client.result.DeleteResult;
import java.util.List;
import javax.annotation.Resource;
import org.apache.commons.collections.CollectionUtils;
import org.rency.crawler.dal.dao.FetchPageDao;
import org.rency.crawler.dal.entity.FetchPageDO;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Repository;

/**
 * 描述: ${TODO}<br>
 * 最近修改时间:2017/11/28 17:55<br>
 *
 * @author CaiyuRen
 * @version V1.0
 * @since 2017/11/28 17:55
 */
@Repository
public class FetchPageDaoImpl implements FetchPageDao {

  @Resource
  private MongoTemplate mongoTemplate;

  @Override
  public FetchPageDO load(String id) {
    Criteria criteria = Criteria.where("id").is(id);
    return mongoTemplate.findOne(new Query(criteria),FetchPageDO.class);
  }

  @Override
  public FetchPageDO find(String docId) {
    Criteria criteria = Criteria.where("docId").is(docId);
    return mongoTemplate.findOne(new Query(criteria),FetchPageDO.class);
  }

  @Override
  public boolean save(FetchPageDO entity) {
    try {
      mongoTemplate.save(entity);
      return true;
    } catch (DuplicateKeyException e) {
      return true;
    }
  }

  @Override
  public boolean save(List<FetchPageDO> entityList) {
    try {
      if(CollectionUtils.isEmpty(entityList)){
        return false;
      }
      mongoTemplate.insertAll(entityList);
      return true;
    } catch (DuplicateKeyException e) {
      return false;
    }
  }

  @Override
  public long findCount() {
    return mongoTemplate.count(new Query(),FetchPageDO.class);
  }

  @Override
  public long removeAll() {
    DeleteResult result = mongoTemplate.remove(new Query(),FetchPageDO.class);
    return result.getDeletedCount();
  }
}
